import { getValue } from "@/config/RedisConfig";
import config from '@/config/index'
import jwt from 'jsonwebtoken'
import fs from 'fs'
import path from 'path'
import { resolve } from "path";

// 验证token
const getJWTPayload = token => {
  return jwt.verify(token.split(' ')[1], config.JWT_SECRET)
}

// 验证验证码
const checkCode = async (sid, code) => {
  const redisData = await getValue(sid)
  if (redisData != null) {
    if (redisData.toLowerCase() === code.toLowerCase()) {
      return true
    }
  }
  return false
}

// 判断目录是否存在
const getStats = (path) => {
  return new Promise((resolve) => {
    fs.stat(path, (err, stats) => {
      if (err) {
        resolve(false)
      } else {
        resolve(stats)
      }
    })
  })
}

// 创建目录
const mkdir = (path) => {
  return new Promise((resolve) => {
    fs.mkdir(path, err => {
      if (err) {
        resolve(false)
      } else {
        resolve(true)
      }
    })
  })
}

// 检测目录是否存在
const dirExist = async (dir) => {
  const isExist = await getStats(dir)
  // 如果该路径存在且不是文件，返回true
  if (isExist && isExist.isDirectory()) {
    return true
  } else if (isExist) {
    //路径存在，但是是文件
    return false
  }
  const tempDir = path.parse(dir).dir

  //如果目录不存在的话，创建目录
  const status = await dirExist(tempDir)

  if (status) {
    const result = await mkdir(dir)
    return result
  } else {
    return false
  }

}

export {
  checkCode,
  getJWTPayload,
  dirExist
}